<template>
  <div class="app-main-container">
    <div class="app-main-title">{{ $route.query.id?$t('message.bjsp'):$t('message.xzsp') }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ $t('message.fhsyy') }}
      </div>
    </div>

    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <el-form-item :label="$t('message.splx2')" prop="type">
        <el-select v-model="param.type" :placeholder="$t('message.qxz') + $t('message.splx2')" :disabled="$route.query.id? true : false" class="w400">
          <el-option :label="$t('message.stsp')" value="1" />
          <el-option :label="$t('message.xlsp')" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="param.type == 2" :label="$t('message.yhj')" prop="coupons_id">
        <el-select v-model="param.coupons_id" :placeholder="$t('message.qxz') + $t('message.yhj')" :disabled="$route.query.id? true : false" class="w400">
          <el-option v-for="(item, index) in yhjList" :key="index" :label="item.couponsName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="param.type == 1" :label="$t('message.spmc')" prop="name">
        <el-input
          v-model="param.name"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.spmc')"
          class="w400"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item v-if="param.type == 1" :label="$t('message.sptp')" prop="img_url">
        <div class="df_ac">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadData"
            :show-file-list="false"
            accept=".jpg,.png"
            :on-change="addFileChange"
          >
            <i class="el-icon-plus uploader-icon" />
            <!-- <div slot="tip" class="el-upload__tip">{{ $t('message.jhpd') }}</div> -->
            <div
              v-show="param.img_url"
              class="file"
              :style="'background-image: url(' + param.img_url + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9">
            <div>{{ $t('message.jycc') }}：{{ '100px X 100px' }}</div>
            <div>{{ $t('message.zctpsm') }}</div>
          </div>
        </div>
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="INTEGRAL_IMG"
            :fixed-number="[32, 32]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
      </el-form-item>
      <el-form-item v-if="param.type == 1" :label="$t('message.spkc')" prop="stock">
        <el-input
          v-model="param.stock"
          class="w400"
          type="number"
          :placeholder="$t('message.qsr') + $t('message.spkc')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.spjf')" prop="price">
        <el-input
          v-model="param.price"
          class="w400"
          type="number"
          :placeholder="$t('message.qsr') + $t('message.spjf')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.sfsj')">
        <el-switch
          v-model="param.status"
          :active-value="'1'"
          :inactive-value="'0'"
        />
      </el-form-item>
      <el-form-item v-if="param.type == 1" :label="$t('message.spxq')" prop="info">
        <div class="secondColor">{{ $t('message.tpbnfz') }}</div>
        <!-- <WangEditor
          ref="myTextEditor"
          :value="param.info"
          @input="(e) => $set(param, 'info', e)"
        /> -->
        <quill-editor
          ref="myTextEditor"
          v-model="param.info"
          :placeholder="$t('message.qsrnr')"
          class="myQuillEditor"
          :options="quillOption"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >{{ $t('message.tj') }}</el-button>
      </el-form-item></el-form>
  </div>
</template>

<script>
import Cropper from '@/components/cropper'
// import WangEditor from '@/components/quillOption'
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {
  uploadFile,
  integralAdd,
  integralEditQuery,
  integralEditSave,
  integralCouponsList
} from '@/api'
export default {
  name: 'IntegralAdd',
  components: {
    quillEditor,
    Cropper
  },
  data() {
    return {
      quillOption: quillConfig,
      subLoading: false,
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      uploadFileUrl: uploadFile,
      param: {
        venueId: sessionStorage.getItem('venueId')
      },
      uploadData: {
        folder: 'INTEGRAL_IMG',
        type: ''
      },
      venueId: sessionStorage.getItem('venueId'),
      yhjList: [],
      rules: {
        pic: [{ required: true, message: this.$t('message.qsc') + this.$t('message.sptp'), trigger: 'change' }],
        img_url: [{ required: true, message: this.$t('message.qsc') + this.$t('message.sptp'), trigger: 'change' }],
        type: [{ required: true, message: this.$t('message.qxz') + this.$t('message.splx'), trigger: 'change' }],
        coupons_id: [{ required: true, message: this.$t('message.qxz') + this.$t('message.yhj'), trigger: 'change' }],
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.spmc'), trigger: 'blur' }],
        stock: [{ pattern: /^\+?[1-9][0-9]*$/, required: true, message: this.$t('message.qsr') + this.$t('message.zqspkc'), trigger: 'blur' }],
        price: [
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, required: true, message: this.$t('message.qsrzrspjf2'), trigger: 'blur' }
        ],
        info: [{ required: true, message: this.$t('message.qsr') + this.$t('message.spxq'), trigger: 'blur' }]
      }
    }
  },
  created() {
    this.integralCouponsList()
    if (this.$route.query.id) {
      this.integralEditQuery(this.$route.query.id)
    }
  },
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被验证前调用
    // 不能获取组件实例 `this` ！
    // 因为当守卫执行时，组件实例还没被创建！
    // to.meta.title = to.query.id ? this.$t('message.bjsp') : this.$t('message.xzsp')
    next()
  },
  methods: {
    integralEditQuery(id) {
      integralEditQuery({
        param: {
          id
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          const obj = { ...res.record }
          this.param = {
            ...obj,
            coupons_id: res.record.couponsId
          }
        })
    },
    integralCouponsList() {
      integralCouponsList({
        param: {
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.yhjList = res.recordList
        })
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.param, 'img_url', res.showUrl)
        this.$set(this.param, 'picture', res.insertUrl)
      } else {
        this.$message.error(res.msg || this.$t('message.scsb'))
      }
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'img_url', config.showUrl)
        this.$set(this.param, 'picture', config.insertUrl)
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'picture', '')
      this.$set(this.param, 'img_url', '')
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.param }
          if (!param.img_url && param.type === '1') {
            return this.$message.info(this.$t('message.qsc') + this.$t('message.sptp'))
          }
          this.subLoading = true
          if (this.$route.query.id) {
            param.id = this.$route.query.id
            integralEditSave({ param: param })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success(this.$t('message.editcg'))
                  this.$router.replace(`/integral/integralList?renovate=1`)
                }
              })
              .catch((er) => {
                this.subLoading = false
                console.log(er)
              })
          } else {
            integralAdd({
              param: param
            })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success(this.$t('message.addcg'))
                  this.$router.replace(`/integral/integralList?renovate=1`)
                }
              })
              .catch((err) => {
                this.subLoading = false
                console.log(err)
              })
          }
        }
      })
    },
    // 返回上一页
    goBack() {
      this.$router.replace(`/integral/integralList`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 50px;
}
</style>
